package com.ketangpai.admin.utils.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域问题
 */
@Configuration
public class GlobalCorsConfig {
    /**
     * 1.设置允许跨域的路径
     * 2.设置允许跨域请求的域名
     * 3.设置允许的方法
     * 4.设置是否允许客户端发送cookie信息。默认是false
     */
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                        .allowCredentials(false);
            }
        };
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
        //添加映射路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();  //1.添加CORS配置信息
        config.setAllowCredentials(true);
        // 使用setAllowedOrigin会出现IllegalArgumentException
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*"); // 允许的头信息
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

}
